﻿using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Core.Common;

namespace TTSClient.Models
{
    class AuthorizationModel
    {
        public AuthorizationModel()
        {
            Date = DateTime.UtcNow.ToString(DateTimeFormatInfo.InvariantInfo.RFC1123Pattern, CultureInfo.CreateSpecificCulture("en-US"));
        }

        private static readonly AppSetting appSetting = AppSetting.Current;
        private string Authorization => $"api_key=\"{APIKey}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{GetSignature()}\"";
        private string Signature => $"host: {Host}\ndate: {Date}\n{RequestLine}";
        private string Date { get; set; }
        private static string Host => appSetting.ApiUri.Host;
        private static string APIKey => appSetting.ApiKey;
        private static string APISecret => appSetting.ApiSecret;
        private static string RequestLine => appSetting.RequestLine;
        private string GetSignature()
        {
            using var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(APISecret));
            var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(Signature));
            return Convert.ToBase64String(bytes);
        }
        public override string ToString()
        {
            return $"{nameof(Authorization).FirstCharToLower()}={Convert.ToBase64String(Encoding.UTF8.GetBytes(Authorization))}&{nameof(Date).FirstCharToLower()}={Date}&{nameof(Host).FirstCharToLower()}={Host}";
        }
    }
}
